package com.jt.serviceimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
import com.jt.service.DubboCartService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class DubboCartServiceImpl implements DubboCartService {

    @Autowired
    private CartMapper cartMapper;

    @Override
    public List<Cart> findObject(Long userId) {
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("user_id", userId);
        return cartMapper.selectList(cartQueryWrapper);
    }

    /**
     * 更新购物车数量 num
     *
     * @param cart
     */
    @Override
    public void updateCartNum(Cart cart) {

        Cart cartTemp = new Cart();
        cartTemp.setNum(cart.getNum());

        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", cart.getUserId())
                .eq("item_id", cart.getItemId());
        cartMapper.update(cartTemp, updateWrapper);
    }

    @Override
    public void deleteCart(Cart cart) {

        cartMapper.delete(new QueryWrapper<>(cart));
    }

    @Override
    public void addCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId())
                .eq("item_id", cart.getItemId());
        Cart cartDB = cartMapper.selectOne(queryWrapper);
        /* 存在商品则数量+1,否则新增商品 */
        if (cartDB != null) {
            cartDB.setNum(cartDB.getNum() + cart.getNum());
//            cartMapper.updateById(cartDB);
            cartMapper.updateCartNum(cartDB);
        } else {
            cartMapper.insert(cart);
        }
    }

    @Override
    public List<Cart> findCartListByUserId(Long userId) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return cartMapper.selectList(queryWrapper);
    }
}
